<template>
  <div class="order order__setting--form">
    <el-form
      :rules="formRules"
      ref="formRef"
      :model="formData"
      label-width="120px"
    >
      <el-form-item label="会员卡名称" prop="title">
        <el-input
          style="width: 200px"
          placeholder="请输入"
          v-model="formData.title"
        ></el-input>
      </el-form-item>
      <el-form-item label="开卡方式" prop="openType">
        <el-radio-group v-model="formData.openType" @change="onOpenTypeChange">
          <el-radio :label="1">付费购买</el-radio>
          <el-radio :label="2">积分兑换</el-radio>
          <!--          <el-radio :label="3">累计消费金额</el-radio>-->
          <!--          <el-radio :label="4">购买指定商品</el-radio>-->
        </el-radio-group>
        <el-table
          :data="formData[tableMap[formData.openType]]"
          style="width: 100%; margin-top: 12px"
        >
          <el-table-column width="60" label="等级">
            <template slot-scope="scope">LV{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="rankName" label="等级名称">
            <template slot-scope="scope">
              <el-input
                :disabled="!scope.row.isOpen"
                v-model="scope.row.rankName"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="radioMap[formData.openType]">
            <template slot-scope="scope">
              <el-input-number
                :min="0"
                :controls="false"
                @blur="comprePre(scope.$index, scope.row, 'payAmount')"
                :disabled="!scope.row.isOpen"
                v-if="formData.openType === 1"
                v-model="scope.row.payAmount"
              >
                <template slot="append">元</template>
              </el-input-number>
              <el-input-number
                :min="0"
                :controls="false"
                @blur="comprePre(scope.$index, scope.row, 'consumeCount')"
                v-if="formData.openType === 3"
                :disabled="!scope.row.isOpen"
                v-model="scope.row.consumeCount"
              >
                <template slot="append">元</template>
              </el-input-number>
              <el-input-number
                :step="1"
                :min="0"
                step-strictly
                :controls="false"
                @blur="comprePre(scope.$index, scope.row, 'integralCount')"
                v-if="formData.openType === 2"
                :disabled="!scope.row.isOpen"
                v-model="scope.row.integralCount"
              >
                <template slot="append">积分</template>
              </el-input-number>
              <el-button
                @click="onSelectGoods(scope.$index)"
                v-if="formData.openType === 4"
                type="text"
                >{{ scope.row.productCount || "选择商品" }}</el-button
              >
            </template>
          </el-table-column>
          <el-table-column width="300" label="会员权益">
            <template slot-scope="scope">
              {{
                scope.row.memberPrivilegeVos &&
                scope.row.memberPrivilegeVos.filter((v) => v.isSelected === 1)
                  .length
                  ? scope.row.memberPrivilegeVos
                      .filter((v) => v.isSelected === 1)
                      .slice(0, 2)
                      .map((v) => v.privilegeName)
                      .join("，") +
                    "等" +
                    (
                      scope.row.memberPrivilegeVos.filter(
                        (v) => v.isSelected === 1,
                      ) || []
                    ).length +
                    "项权益"
                  : ""
              }}
              <el-button
                @click="onChangeRequity(scope.row, scope.$index)"
                type="text"
                size="small"
              >
                {{
                  scope.row.isOpen
                    ? !scope.row.memberPrivilegeVos ||
                      !scope.row.memberPrivilegeVos.length
                      ? "选择权益"
                      : "修改"
                    : null
                }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                @click="handelLevelSet(scope.row, scope.$index)"
                type="text"
                size="small"
                >设置</el-button
              >

              <el-button
                @click="handelChangeStatus(scope.row, scope.$index)"
                type="text"
                size="small"
                >{{ scope.row.isOpen ? "停用" : "启用" }}</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div v-if="formData.openType == 4" style="color: #999; font-size: 12px">
          购买指定任一商品即可成为会员
        </div>
        <!-- <el-button class="setupcon__item3--addnew"
                   type="text"
                   @click="addLevel">新增等级
        </el-button>-->
      </el-form-item>
      <el-form-item label="注册表单" required>
        <el-table :data="forms" style="width: 100%">
          <el-table-column prop="formName" label="表单名称"></el-table-column>
          <el-table-column prop="formPattern" label="表单格式">
            <template slot-scope="scope">
              {{ getFormName(scope.row.formPattern) }}
            </template>
          </el-table-column>
          <el-table-column label="必填" prop="isRequired">
            <template slot-scope="scope">
              {{ scope.row.isRequired == 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column label="提示语" prop="tips"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                @click="handleEdit(scope.row, scope.$index)"
                type="text"
                size="small"
                :disabled="scope.row.formId == 1"
                >编辑</el-button
              >

              <el-button
                @click="handleDel(scope.row, scope.$index)"
                type="text"
                size="small"
                :disabled="scope.row.formId == 1"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <el-button
          class="setupcon__item3--addnew"
          type="text"
          @click="toggleDialogVisible"
          >添加</el-button
        >
      </el-form-item>
      <el-form-item label="有效期" prop="useInDate">
        <el-input-number
          :step="1"
          :min="0"
          step-strictly
          :controls="false"
          style="width: 200px"
          v-model="formData.useInDate"
        ></el-input-number
        >&nbsp;&nbsp;天
      </el-form-item>
      <el-form-item label=" ">
        <el-button @click="onSaveCard" type="primary">保存</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="自定义表单" :visible.sync="formDialogVisible" width="30%">
      <el-form
        ref="coustomFormRef"
        :rules="coustomRules"
        :model="coustomForm"
        label-width="80px"
      >
        <el-form-item label="表单名称" prop="formName" required>
          <el-input v-model="coustomForm.formName"></el-input>
        </el-form-item>
        <el-form-item label="表单格式" prop="formPattern" required>
          <el-select
            v-model="coustomForm.formPattern"
            style="width: 100%"
            placeholder="请选择"
          >
            <el-option
              v-for="item of formOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否必填" prop="isRequired">
          <el-radio-group v-model="coustomForm.isRequired">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="2">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="提示语" prop="tips">
          <el-input v-model="coustomForm.tips"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="toggleDialogVisible">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="背景设置" :visible.sync="cardDialogVisible" width="30%">
      <el-form label-position="top" label-width="80px" :model="currentCardData">
        <el-form-item label>
          <el-radio-group v-model="currentCardData.style">
            <el-radio label="1">系统风格</el-radio>
            <el-radio label="2">自定义风格</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="currentCardData.style == '1'" label>
          <span
            v-for="item in sysImgs"
            :key="item"
            :class="item === currentCardData.img ? 'sImg aImg' : 'sImg'"
          >
            <img width="40" height="40" :src="item" @click="imgClick(item)" />
          </span>
        </el-form-item>
        <el-form-item v-if="currentCardData.style == '2'" label>
          <div class="product" style="display: flex">
            <el-upload
              class="productImg__uploader product__productImg"
              :auto-upload="false"
              :on-change="addUploadBigProductImg"
              action
              :show-file-list="false"
              style="width: 100px; height: 120px"
            >
              <img
                v-if="currentCardData.cusImg"
                :src="currentCardData.cusImg"
                class="product__productImg"
                style="width: 100px; height: 120px"
              />
              <i
                class="el-icon-plus product__productImg--uploader--icon"
                v-if="!currentCardData.cusImg"
                style="
                  width: 100px;
                  line-height: 100px;
                  border: 1px dotted #999;
                "
              ></i>
            </el-upload>
          </div>
          <div class="text-info fs-12" style="color: rgba(69, 64, 60, 0.6)">
            最佳尺寸682*370，图片大小不超过150kb
          </div>
        </el-form-item>
        <el-form-item label="预览效果">
          <img
            width="160"
            v-show="currentCardData.img && currentCardData.style == '1'"
            :src="currentCardData.img"
          />
          <img
            width="160"
            v-show="currentCardData.cusImg && currentCardData.style == '2'"
            :src="currentCardData.cusImg"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onCardOk">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="选择权益" :visible.sync="requityVisible" width="30%">
      <div>
        <el-checkbox-group
          class="cCheckbox"
          :border="false"
          @change="privilegeChange"
          v-model="selectRowChecked"
        >
          <el-checkbox
            v-for="item in selectRow.memberPrivilegeVos"
            :class="item.open == 0 && 'no-show'"
            :label="item.id"
            :key="item.id"
          >
            {{ item.privilegeName }}
            <el-input-number
              :min="10"
              :max="99"
              :controls="false"
              style="width: 200px; vertical-align: middle"
              v-if="item.ptype === '1' && item.isSelected"
              placeholder="输入10-99之间数字"
              v-model="item.value"
            >
              <template slot="append">%</template>
            </el-input-number>
            <el-input-number
              :min="2"
              :max="50"
              :step="1"
              step-strictly
              :controls="false"
              style="width: 200px; vertical-align: middle"
              v-if="item.ptype === '3' && item.isSelected"
              placeholder="输入2-50之间数字"
              v-model="item.value"
            >
              <template slot="append">倍</template>
            </el-input-number>
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onRequityOk">确 定</el-button>
      </span>
    </el-dialog>
    <SelectGoods
      :pointGoodsList="pointGoodsList"
      :allIds="allIds"
      ref="goodsDialog"
      @onSureGoods="onSureGoods"
    />
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch, Ref } from "vue-property-decorator";
// import { getOrderSetting } from "@/api/finance";
import { upLoad } from "@/api";
import cloneDeep from "lodash/cloneDeep";
import { readFile, advanceGetImage } from "@/store/modules/voidImg";
import SelectGoods from "../dialog/SelectGoods.vue";
import {
  getMemberCard,
  saveMemberCard,
  updateMemberCardInfoStatus,
  getMemberCardPrivilege,
} from "@/api/customer/member";
import { commonMemberList } from "@/libs/const";

@Component({ components: { SelectGoods } })
export default class Order extends Vue {
  @Ref() readonly goodsDialog;

  @Ref() readonly formRef: HTMLFormElement;

  @Ref() readonly coustomFormRef: HTMLFormElement;

  // 默认注册表单状态
  coustomForm = {
    formName: "",
    formPattern: null,
    isRequired: 2,
    tips: "请输入",
  };

  currentForm = null;

  // 当前编辑的卡片行数据
  currentCardData: { [propName: string]: any } = {
    style: "1",
  };

  // 当前编辑的卡片行
  currentCardindex = 0;

  // 当前操作的表单
  currentIndex = 0;

  // 注册表单的校验规则
  coustomRules = {
    formName: [
      {
        required: true,
        message: "表单名称不可为空",
        // trigger: "blur",
      },
    ],
    formPattern: [
      {
        required: true,
        message: "表单类型不可为空",
        // trigger: "change",
      },
    ],
  };

  // 注册表单modal显示
  formDialogVisible = false;

  // 会员卡设置modal显示
  cardDialogVisible = false;

  // 权益modal显示
  requityVisible = false;

  // 表单格式选项
  formOptions = [
    {
      label: "电话",
      value: 3,
    },
    {
      label: "身份证",
      value: 1,
    },
    {
      label: "文本",
      value: 2,
    },
  ];

  // 开卡方式MAP
  radioMap = {
    1: "付费金额",
    2: "积分",
    3: "累计消费",
    4: "选择商品",
  };

  // 会员卡取值map
  tableMap = {
    1: "paymentVos",
    2: "integralVos",
    3: "consumeVos",
    4: "assignProductVos",
  };

  // 选中的行
  selectRow: any = {};

  selectRowChecked = [];

  allIds = [];

  // 默认表单内容
  formData = {
    title: "",
    openType: 1,
    integralVos: null,
    consumeVos: null,
    assignProductVos: null,
    memberRegisterFormVos: [
      {
        id: "1",
        formId: "1",
        formName: "手机号",
        formPattern: 3,
        isRequired: 1,
        tips: "请输入手机号",
      },
      {
        id: "2",
        formId: "2",
        formName: "身份证",
        formPattern: 1,
        isRequired: 2,
        tips: "请输入身份证号",
      },
    ],
    useInDate: "365",
    useAmount: null,
  };

  // 记录前一次的开卡方式
  preOpenType = 2;

  // 校验规则
  formRules: any = {
    title: [{ required: true, message: "请输入会员卡名称", trigger: "blur" }],
    openType: [{ required: true, message: "请选择开卡方式", trigger: "blur" }],
    useInDate: [{ required: true, message: "请输入有效期", trigger: "blur" }],
  };

  // 选中的商品
  pointGoodsList = [];

  // 权益列表
  requities = [];

  // 注册表单默认数据
  forms = [
    {
      formId: 1,
      formName: "手机号",
      formPattern: 3,
      isRequired: 1,
      tips: "请输入手机号",
    },
  ];

  // 输入框递增校验
  comprePre(index, row, type) {
    const tableData = this.formData[this.tableMap[this.formData.openType]];
    try {
      if (
        index !== 0 &&
        parseInt(tableData[index - 1][type]) > parseInt(row[type])
      ) {
        this.$message.error("不能小于前一项");
      }
    } catch {}
  }

  // 默认的系统会员头像
  sysImgs = [
    "https://oss-tencent.bgniao.cn/api/general_card.png",
    "https://oss-tencent.bgniao.cn/api/silver_card.png",
    "https://oss-tencent.bgniao.cn/api/gold_card.png",
    "https://oss-tencent.bgniao.cn/api/platinum_card.png",
    "https://oss-tencent.bgniao.cn/api/supremacy_card.png",
  ];

  created() {
    getMemberCard(null).then((res) => {
      const newData = cloneDeep(res.data);
      const openType = newData.openType || 1;
      this.preOpenType = openType;
      const memberCardList =
        newData[this.tableMap[openType]] || commonMemberList;
      newData[this.tableMap[openType]] = this.getDefaultImg(memberCardList);
      this.formData = newData;
      if (
        res.data.memberRegisterFormVos &&
        res.data.memberRegisterFormVos.length > 0
      ) {
        this.forms = res.data.memberRegisterFormVos;
      }
    });
    getMemberCardPrivilege(null).then((res) => {
      this.requities = res.data;
    });
  }

  getDefaultImg(arr) {
    return arr.map((v, i) => {
      v.backGroundPicUrl = v.backGroundPicUrl || this.sysImgs[i];
      v.style = v.style ? v.style + "" : "1";
      return v;
    });
  }

  // 开卡方式change事件
  onOpenTypeChange(val) {
    // this.formData[this.tableMap[val]] = this.formData[
    //   this.tableMap[this.preOpenType]
    // ];
    this.preOpenType = val;
  }

  // 点击背景设置的图片
  imgClick(item) {
    this.currentCardData.img = item;
    this.currentCardData = cloneDeep(this.currentCardData);
  }

  @Watch("formDialogVisible")
  handleDialogVisible(v) {
    if (!v) {
      this.currentForm = null;
      this.resetCoustomForm();
    }
  }

  @Watch("cardDialogVisible")
  handleCardDialogVisible(v) {
    if (!v) {
      this.currentCardData = {};
    }
  }

  // 添加会员等级
  // addLevel() {
  //   const newMembers = [...this.formData.members, { name: "", cost: null, equities: [], type: "", img: "" }];
  //   this.formData = { ...this.formData, members: newMembers };
  // }

  // 删除会员等级
  // handleDelLevel(index) {
  //   this.formData.members.splice(index, 1);
  // }

  getPrivilegeValue(index, pType) {
    const tableData = this.formData[this.tableMap[this.formData.openType]];
    if (tableData[index].isOpen == 0) {
      return null;
    }
    const privileges = tableData[index].memberPrivilegeVos;
    let value = null;
    privileges.forEach((el) => {
      el.ptype == pType && (value = el.value);
    });
    return value;
  }

  // 权益设置modal确认
  onRequityOk() {
    if (this.selectRow.memberPrivilegeVos.every((v) => v.isSelected == 0)) {
      this.$message.error("至少选择一项权益");
      return null;
    }
    const rowIndex = this.selectRow.rowIndex;
    let isRequired = true;
    let isValidDisValue = true;
    let isNumber = true;
    let isValidIntValue = true;
    let compareDisValue = true;
    let compareIntValue = true;
    this.selectRow.memberPrivilegeVos.forEach((item) => {
      if (
        (item.ptype == 1 && item.isSelected == 1) ||
        (item.ptype == 3 && item.isSelected == 1)
      ) {
        !item.value && (isRequired = false);
        isNaN(item.value) && (isNumber = false);
      }
      if (item.ptype == 1 && item.isSelected == 1 && !isNaN(item.value)) {
        (Number(item.value) > 99 || Number(item.value) < 10) &&
          (isValidDisValue = false);
        (item.value + "").indexOf(".") !== -1 && (isValidDisValue = false);
        for (let i = 0; i <= 4; i++) {
          if (!this.getPrivilegeValue(i, 1)) {
            break;
          }
          if (i < rowIndex) {
            if (Number(item.value) > Number(this.getPrivilegeValue(i, 1))) {
              compareDisValue = false;
            }
          }
          if (i > rowIndex) {
            if (Number(item.value) < Number(this.getPrivilegeValue(i, 1))) {
              compareDisValue = false;
            }
          }
        }
      }
      if (item.ptype == 3 && item.isSelected == 1 && !isNaN(item.value)) {
        const valArr = (item.value + "").split(".");
        valArr[1] && valArr[1].length > 1 && (isValidIntValue = false);
        (Number(item.value) > 50 || Number(item.value) < 2) &&
          (isValidIntValue = false);
        for (let i = 0; i <= 4; i++) {
          if (!this.getPrivilegeValue(i, 3)) {
            break;
          }
          if (i < rowIndex) {
            if (Number(item.value) < Number(this.getPrivilegeValue(i, 3))) {
              compareIntValue = false;
            }
          }
          if (i > rowIndex) {
            if (Number(item.value) > Number(this.getPrivilegeValue(i, 3))) {
              compareIntValue = false;
            }
          }
        }
      }
    });
    if (!isRequired) {
      this.$message.error("输入框值必填");
      return null;
    }

    if (!isNumber) {
      this.$message.error("不能输入非数字字符");
      return null;
    }

    if (!isValidDisValue) {
      this.$message.error("折扣值必须为10-99整数");
      return null;
    }

    if (!isValidIntValue) {
      this.$message.error("积分只允许2-50且保留小数点后一位的数值");
      return null;
    }

    if (!compareDisValue) {
      this.$message.error(
        "折扣值需小于等于低等级折扣权益值且大于等于高等级折扣权益值",
      );
      return null;
    }

    if (!compareIntValue) {
      this.$message.error(
        "积分值需大于等于低等级积分权益值且小于等于高等级积分权益值",
      );
      return null;
    }
    const formData = cloneDeep(this.formData);
    formData[this.tableMap[formData.openType]][rowIndex] = this.selectRow;
    this.formData = formData;
    this.requityVisible = false;
  }

  // 改变会员状态
  handelChangeStatus(rowData, index) {
    const formData = cloneDeep(this.formData);
    if (rowData.isOpen) {
      // for (let i = 0; i < index; i++) {
      //   if (
      //     formData[this.tableMap[formData.openType]][i] &&
      //     formData[this.tableMap[formData.openType]][i].isOpen
      //   ) {
      //     this.$message({
      //       type: "warning",
      //       message: "需要先停用低等级会员",
      //     });
      //     return false;
      //   }
      // }
      this.$confirm("停用等级小程序端将不会显示该等级，确定停用吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        updateMemberCardInfoStatus([
          {
            rankCode: rowData.rankCode,
            memberCardInfoSwitch: 0,
          },
        ])
          .then(() => {
            formData[this.tableMap[formData.openType]][index].isOpen = 0;
            this.formData = formData;
          })
          .catch((msg) => {
            this.$message({
              type: "error",
              message: msg,
            });
          });
      });
    } else {
      // for (
      //   let i = index + 1;
      //   i < formData[this.tableMap[formData.openType]].length;
      //   i++
      // ) {
      //   if (!formData[this.tableMap[formData.openType]][i].isOpen) {
      //     this.$message({
      //       type: "warning",
      //       message: "需要先开启高等级会员",
      //     });
      //     return false;
      //   }
      // }
      this.$confirm("启用等级后将正常使用该等级权益，确定启用吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        updateMemberCardInfoStatus([
          {
            rankCode: rowData.rankCode,
            memberCardInfoSwitch: 1,
          },
        ]).then(() => {
          formData[this.tableMap[formData.openType]][index].isOpen = 1;
          this.formData = formData;
        });
      });
    }
  }

  // 设置会员等级
  handelLevelSet(rowData, index) {
    // this.radioStyle = rowData.style ? rowData.style + '' : "1";
    this.currentCardData = {
      style: rowData.style ? rowData.style + "" : "1",
      img:
        rowData.style == "1" ? rowData.backGroundPicUrl : this.sysImgs[index],
      cusImg: rowData.style == "2" ? rowData.backGroundPicUrl : "",
    };
    this.currentCardindex = index;
    this.cardDialogVisible = true;
  }

  // 确定设置会员
  onCardOk() {
    const formData = cloneDeep(this.formData);
    formData[this.tableMap[formData.openType]][this.currentCardindex].style =
      this.currentCardData.style;
    if (this.currentCardData.style == "1") {
      formData[this.tableMap[formData.openType]][
        this.currentCardindex
      ].backGroundPicUrl = this.currentCardData.img;
    } else {
      formData[this.tableMap[formData.openType]][
        this.currentCardindex
      ].backGroundPicUrl = this.currentCardData.cusImg;
    }
    this.formData = formData;
    this.cardDialogVisible = false;
  }

  // 选中的商品
  onSelectGoods(index) {
    let allIds = "";
    this.currentHandelGoodIndex = index;
    (this.formData.assignProductVos || []).forEach((item, i) => {
      if (index != i) {
        allIds += item.memberCardGoodsVo
          ? `,${item.memberCardGoodsVo.goodsIds}` || ""
          : "";
      }
    });
    const ids = this.formData.assignProductVos[index].memberCardGoodsVo
      ? this.formData.assignProductVos[index].memberCardGoodsVo.goodsIds
      : "";
    this.allIds = allIds.split(",");
    this.pointGoodsList = ids
      .split(",")
      .map((v) => ({ id: v }))
      .filter((v) => !!v.id);
    this.goodsDialog.init();
  }

  // 商品modal确认
  onSureGoods(pointGoodIds) {
    const formData = cloneDeep(this.formData);
    formData.assignProductVos[this.currentHandelGoodIndex].memberCardGoodsVo = {
      goodsIds: pointGoodIds.join(","),
    };
    formData.assignProductVos[this.currentHandelGoodIndex].productCount =
      pointGoodIds.length;
    this.formData = formData;
  }

  // 修改权益
  onChangeRequity(row, index) {
    this.requityVisible = true;
    this.selectRow = cloneDeep(row);
    this.selectRow.rowIndex = index;
    if (
      !this.selectRow.memberPrivilegeVos ||
      !this.selectRow.memberPrivilegeVos.length
    ) {
      this.selectRow.memberPrivilegeVos = cloneDeep(this.requities);
    }
    this.selectRowChecked = (this.selectRow.memberPrivilegeVos || [])
      .filter((v) => v.isSelected == "1")
      .map((v) => v.id);
  }

  // 权益change
  privilegeChange(s) {
    this.selectRow.memberPrivilegeVos = this.selectRow.memberPrivilegeVos.map(
      (v) => {
        v.isSelected = 0;
        if ((s || []).some((vv) => vv == v.id)) {
          v.isSelected = 1;
        }
        return v;
      },
    );
  }

  /**
   * 上传大图片
   */
  async addUploadBigProductImg(file) {
    const whiteList = ["image/jpeg", "image/jpg", "image/png"];

    const isLt1M = file.size < 1024 * 1024;
    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传文件只能是 JPG或PNG 格式!");
      return;
    }
    if (!isLt1M) {
      this.$message.error("上传文件大小不能超过 1MB!");
      return;
    }

    const imgFile = await readFile(file.raw);
    const newImg = await advanceGetImage(imgFile);
    if (newImg.image.width !== 682 || newImg.image.height !== 370) {
      this.$message.error("宽屏图片长宽应为682*370");
      return;
    }

    const res = await upLoad({
      file: file.raw,
    });
    this.currentCardData.cusImg = res.data;
  }

  // 重置注册表单
  resetCoustomForm() {
    this.coustomForm = {
      formName: "",
      formPattern: null,
      isRequired: 2,
      tips: "请输入",
    };
  }

  //表单格式映射
  getFormName(key) {
    const data = this.formOptions.find((item) => item.value === key);
    return data && data.label;
  }

  toggleDialogVisible() {
    this.formDialogVisible = !this.formDialogVisible;
  }

  // 其定义表单modal确认
  async onConfirm() {
    await this.formValidate(this.coustomFormRef);
    (this.$refs.coustomFormRef as any).validate((valid) => {
      if (!valid) {
        return this.$message.info("请填写正确的表单");
      }
      if (!this.currentForm) {
        this.forms.push({ ...this.coustomForm, formId: this.forms.length + 1 });
      } else {
        this.$set(
          this.forms,
          this.currentIndex,
          cloneDeep({
            ...this.coustomForm,
            formId: this.currentIndex + 1 + "",
          }),
        );
      }

      this.toggleDialogVisible();
    });
  }

  // 注册表单列表删除
  handleDel(item, i) {
    this.forms.splice(i, 1);
  }

  // 注册表单列表编辑
  handleEdit(item, i) {
    this.currentForm = cloneDeep(item);
    this.coustomForm = this.currentForm;
    this.currentIndex = i;
    this.toggleDialogVisible();
  }

  /**
   * 对整个表单进行校验
   */
  formValidate(formType) {
    return formType.validate();
  }

  // 会员卡信息保存
  async onSaveCard() {
    await this.formValidate(this.formRef);
    const tableData = this.formData[this.tableMap[this.formData.openType]];
    let isPass = true;
    let isSort = true;
    const valueMap = {
      1: "payAmount",
      2: "integralCount",
      3: "consumeCount",
      4: "productCount",
    };
    tableData.forEach((v) => {
      if (v.isOpen == 1) {
        if (!v.rankName || !v[valueMap[this.formData.openType]]) {
          isPass = false;
        }
      }
    });
    !isPass && this.$message.error("请填写完整会员卡数据");

    // 处理文本框数值是否递增
    if (isPass && this.formData.openType != 4) {
      for (let i = 1; i < tableData.length; i++) {
        if (tableData[i].isOpen == 1) {
          if (
            Number(tableData[i][valueMap[this.formData.openType]]) <
            Number(tableData[i - 1][valueMap[this.formData.openType]])
          ) {
            isSort = false;
          }
        }
      }
      !isSort && this.$message.error("会员卡值金额或积分需递增");
    }
    const privilegeNumList = tableData
      .filter((i) => i.isOpen)
      .map((item) => {
        return item.memberPrivilegeVos.filter((v) => v.isSelected === 1).length;
      });
    let isUp = true;
    privilegeNumList.forEach((number, index, array) => {
      let next = array[index + 1];
      if (next !== undefined && number > next) {
        isUp = false;
        this.$message.error("存在高等级会员权益比低等级会员权益少");
      }
    });
    if (isPass && isSort && isUp) {
      saveMemberCard({
        ...this.formData,
        memberRegisterFormVos: this.forms,
      }).then((res) => {
        res.code === 200 &&
          this.$message({
            type: "success",
            message: "保存成功",
          });
      });
    }
  }
}
</script>

<style lang="scss">
@include b(sImg) {
  display: inline-block;
  padding: 6px;
  width: 60px;
  height: 60px;
  margin-right: 12px;
  border: 1px solid #999;
  > img {
    cursor: pointer;
  }
}
@include b(aImg) {
  border: 1px solid #409eff;
}
@include b(cTable) {
  border: 1px solid #999;
  border-radius: 4px;
  width: 100%;
  padding: 0 12px;
  @include e(row) {
    border-bottom: 1px solid #999;
    margin: 9px 0;
    &:last-child {
      border-bottom: none;
    }
    &:first-child {
      padding-bottom: 9px;
    }
    @include m(col) {
      float: left;
      /deep/ .el-button {
        display: block;
        // padding: 9px 0;
        padding: 0;
        font-size: 14px;
        margin: 0 0 9px;
      }
      > span {
        display: block;
        // padding: 9px 0;
        margin-bottom: 9px;
      }
      > i {
        display: inline-block;
        font-style: normal;
        vertical-align: middle;
      }
    }
  }
}
@include b(cCheckbox) {
  > label {
    display: block;
    line-height: 40px;
    height: 40px;
    // vertical-align: middle;
  }
}
.order__setting--form {
  font-size: 13px;

  .el-table .cell {
    padding: 10px;
  }

  .order__tip {
    vertical-align: center;
    background-color: rgba(246, 248, 250, 1);
    padding: 15px 15px 15px 30px;
    margin-bottom: 30px;

    .order__tip--title {
      margin-left: 12px;
      color: #586884;
      font-weight: 700;
    }
  }

  .el-table--fit {
    border: 1px solid #e4e4e4;
    border-bottom: 0px;
  }

  .el-table td,
  .el-table th {
    padding: 0 !important;
  }

  .el-table th {
    padding: 0 !important;
    background-color: #f2f4f3 !important;
  }

  .el-table__header-wrapper tr {
    background-color: #f2f4f3 !important;
  }

  .el-form {
    margin-bottom: 40px;
  }
}

.order__tip--lump {
  display: inline-block;
  width: 3px;
  height: 12px;
  background-color: rgba(255, 153, 0, 1);
}
.no-show {
  display: none !important;
}
</style>
